import {weapi} from './util/crypto';
import {NativeModules} from 'react-native';

let localCookie = "";
module.exports = async function requestAPI(url, data, cookie = '',cry = true) {
  if(cry){
    data = weapi(data);
  }
  if(url.indexOf('/login/cellphone') === -1) {
    if (localCookie === "" || url.indexOf('/account/get') !== -1) {
      await NativeModules.ToolModule.checkNetease().then((r) => {
        if (r.cookie) {
          localCookie = r.cookie;
        }else{
          localCookie = "";
        }
        cookie = localCookie;
        //console.log(r);
      });
    }
    cookie = localCookie;
  }

  //console.log(cookie);
  return NativeModules.ToolModule.sendNetease(url, data, cookie)
    .then(r => {
      //console.log(r);
      if (r.body) {
        // eslint-disable-next-line no-eval
        let result =  JSON.parse(r.body);
        if(r.cookie){
          result.cookie = r.cookie;
        }
        return result;
      }
      return r;
    })
    .catch(r => {
      //console.log(r);
    });
};
